package com.bean;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import java.util.List;
import java.util.stream.Collectors;

public class ObjectMapperUtils {

    private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();

    static {
        OBJECT_MAPPER.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    }

    public static <T> T clone(T obejct) {
        T result = (T) jsonToObject(obejct, obejct.getClass());
        return result;
    }

    public static <T> T clone(Object obejct, Class<T> tClass) {
        T result = (T) jsonToObject(obejct, tClass);
        return result;
    }

    public static <T> T clone(Object obejct, TypeReference<T> type) {
        T result = (T) jsonToObject(obejct, type);
        return result;
    }

    public static <T> List<T> clones(List<?> objects, Class<T> tClass) {
        List<T> collect = objects.stream().map(o -> clone(o, tClass)).collect(Collectors.toList());
        return collect;
    }

    public static <T> T jsonToObject(Object obejct, Class<T> tClass) {
        if (null == obejct) {
            return null;
        }
        String jsonString = JSON.toJSON(obejct).toString();
        if (StringUtils.isEmpty(jsonString)) {
            return null;
        }
        try {
            T cloneObj = OBJECT_MAPPER.readValue(jsonString, tClass);
            return cloneObj;
        } catch (JsonProcessingException e) {
            e.printStackTrace();
            return null;
        }
    }

    public static <T> T jsonToObject(Object obejct, TypeReference<T> type) {
        if (null == obejct) {
            return null;
        }
        String jsonString = JSON.toJSON(obejct).toString();
        if (StringUtils.isEmpty(jsonString)) {
            return null;
        }
        try {
            T t = JSONObject.parseObject(jsonString, type);
            return t;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

}
